package servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import dto.RentDto;
import entity.Rent;
import service.RentService;
import service.impl.RentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/add")
public class Add extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();
        StringBuilder json = new StringBuilder();
        String line = null;
        try {
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) { /* handle exception */ }

        // 解析JSON字符串为Java对象或其他处理方式
        JSONObject jsonObject = JSON.parseObject(json.toString());

        Rent rent = jsonObject.toJavaObject(Rent.class);
        RentService rentService = new RentServiceImpl();


        int add = rentService.add(rent);
        System.out.println(add);

        if (add>0){
            RentDto rentDto=new RentDto("200","添加成功",null);
            out.write(JSON.toJSONString(rentDto));
        }else {
            RentDto rentDto=new RentDto("500","添加失败",null);
            out.write(JSON.toJSONString(rentDto));
        }
        out.flush();
        out.close();

    }
}
